package threading.tests;

import org.junit.*;
import java.util.concurrent.atomic.*;

import jccr.*;

public class ChoiceCoordinatorTests extends TestUnitBase {

	@Test
	public void choiceP1P2() throws Exception {		
		
		String p1t = "P1", p2t = "P2";
		choice(_p1, p1t, _p2, p2t);				
	}
	
	@Test
	public void choiceP2P1() throws Exception {		
		
		String p1t = "P1", p2t = "P2";
		choice(_p2, p2t, _p1, p1t);				
	}
	
	@Test
	public void choiceP1P2PreEnqueued() throws Exception {
		
		newLatch();
		
		String p1t = "P1", p2t = "P2";
		_p1.enqueue(p1t);		
		_p2.enqueue(p2t);
		
		_coord.choice(_p1, _p2);
		
		awaitLatch();
		
		assertEquals( 1, _p1.callCount() );			
		assertEquals( 0, _p2.callCount() );
		
		assertEquals( 0, _p1.count() );
		assertEquals( 1, _p2.count() );
	}
	
	void choice( TracePort p1, String p1t, TracePort p2, String p2t ) throws Exception {
		
		newLatch(1);
		_coord.choice(p1, p2);		
		
		p1.enqueue(p1t);
		Thread.yield();		
		p2.enqueue(p2t);
	
		awaitLatch();
		 
		assertEquals( 1, p1.callCount() );			
		assertEquals( 0, p2.callCount() );
		
		assertEquals( 0, p1.count() );
		assertEquals( 1, p2.count() );
	}	
	
	
	@Override
	public void setup() {
		super.setup();
		
		_p1 = new TracePort();
		_p2 = new TracePort();		
	}
		
	TracePort _p1;
	TracePort _p2;	
	String _arg;
}
